package Threads;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class FutureTaskTest {
    public static void main(String[] args) {

        // 创建Callable接口实现类的实例
        Callable<Integer> sumTask = new SumTask();

        // 使用FutureTask类包装Callable接口实现类的实例
        FutureTask<Integer> futureTask = new FutureTask<Integer>(sumTask);

        // 使用线程执行任务
        Thread thread = new Thread(futureTask);
        thread.start();

        // 获取线程执行结果
        try {
            Object sum = futureTask.get();
            System.out.println("sum = " + sum);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }
}

class SumTask implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + " -> " + i);
            sum += i;
        }
        return sum;
    }
}
